<template>
  <div>
    <div>
      <div class="flex-r" v-for="(choice,index) in choices" :key="choice.value">
        <div :style="{paddingLeft:`${choice.level * 24}px`}">
          <mu-checkbox v-model="inSideValue"
                       :value="choice.value" :label="choice.label"
                       @click="rebuild(index)"
          >
          </mu-checkbox>
        </div>
      </div>
    </div>
  </div>
</template>

<script >
export default {
  name: "EzTreeSelect",
  props:{
    value: {},
    config: {}
  },
  data() {
    return {
      inSideValue: [],
      choices:[],
    }
  },
  mounted() {
    if (this.$utils.isArray(this.value)){
      this.inSideValue = this.value
    }else {
      this.inSideValue = []
    }
    //检查是否设置了数据接口，如果是则从接口获取数据
    if (this.config.api === ""){
      this.choices = this.config.choices
    }else {
      this.config.apiParams.limit = this.config.apiParams.limit?this.config.apiParams.limit:1000
      this.config.apiParams.page = this.config.apiParams.page?this.config.apiParams.page:1
      this.$http.post(this.config.api,this.config.apiParams,res=>{
        this.choices = this.config.apiCbFunc(res.data.lists)
      })
    }
  },
  created() {
  },
  methods: {
    //重新梳理数据
    rebuild(v) {
      let curChoice = this.choices[v]
      if (this.inSideValue.indexOf(curChoice.value) > -1){
        //选项被加入后
        //1.检查他的父节点是否被选中
        if (curChoice.parent > 0){
          this.selectAllParent(curChoice.parent)
        }
        //2.如果父节点被选中，将当前选项加入到父节点的子节点中
        this.selectAllChild(curChoice.value)
      }else {
        //移除所有选项
        this.removeAllChild(curChoice.value)
      }

    },
    selectAllParent(parentId){
      for (let i = 0; i < this.choices.length; i++) {
        let curChoice = this.choices[i]
        if (curChoice.value === parentId){
          if (this.inSideValue.indexOf(curChoice.value) === -1){
            this.inSideValue.push(curChoice.value)
          }
          if (curChoice.parent > 0){
            this.selectAllParent(curChoice.parent)
          }
        }
      }
    },
    selectAllChild(parentId){
      for (let i = 0; i < this.choices.length; i++) {
        let curChoice = this.choices[i]
        if (curChoice.parent === parentId){
          if (this.inSideValue.indexOf(curChoice.value) === -1){
            this.inSideValue.push(curChoice.value)
          }
          this.selectAllChild(curChoice.value)
        }
      }
    },
    removeAllChild(parentId){
      for (let i = 0; i < this.choices.length; i++) {
        let curChoice = this.choices[i]
        if (curChoice.parent === parentId){
          this.inSideValue.splice(this.inSideValue.indexOf(curChoice.value),1)
          this.removeAllChild(curChoice.value)
        }
      }
    }
  },
  watch: {
    inSideValue(val) {
      this.$emit("input", val)
    }
  },
}
</script>

<style scoped>

</style>